import { Component, OnInit, Injector, } from '@angular/core';
import {
    DictionaryItemServiceProxy,
    CreateOrUpdateDictionaryItemInput
} from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import { ModalComponentBase } from '@shared/common/modal-component-base';

export interface IDictionaryItemOnEdit {
    id?: number;
    parentId?: number;
    name?: string;
    code?: string;
    sortCode?: number;
    parentName?: string;
}

@Component({
    selector: 'createOrEditDictionaryItemModal',
    templateUrl: './create-or-edit-dictionary-item-modal.component.html',
    styles: [],
})
export class CreateOrEditDictionaryItemModalComponent extends ModalComponentBase implements OnInit {

    dictionaryItem: IDictionaryItemOnEdit = {};
    saving = false;

    constructor(
        injector: Injector,
        private DictionaryItemService: DictionaryItemServiceProxy,
    ) {
        super(injector);
    }

    ngOnInit() { }

    save(): void {
        this.createOrUpdateDictionaryItem();
    }

    createOrUpdateDictionaryItem(): any {
        const updateInput = new CreateOrUpdateDictionaryItemInput();
        updateInput.dictionaryItem.id = this.dictionaryItem.id;
        updateInput.dictionaryItem.name = this.dictionaryItem.name;
        updateInput.dictionaryItem.parentId = this.dictionaryItem.parentId;
        updateInput.dictionaryItem.code = this.dictionaryItem.code;
        updateInput.dictionaryItem.sortCode = this.dictionaryItem.sortCode;
        this.saving = true;
        this.DictionaryItemService
            .createOrUpdate(updateInput)
            .pipe(finalize(() => (this.saving = false)))
            .subscribe(result => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.success(result);
            });
    }
}
